﻿using OfficeOpenXml;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace HundSunDBQryFrmClient.Utils
{
    internal class ExcelHelp
    {
        internal static void writeExcel(DataTable dataTable, string filePath)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            // 创建一个新的Excel包
            using (var package = new ExcelPackage())
            {
                // 添加一个工作表
                var worksheet = package.Workbook.Worksheets.Add("Sheet1");

                // 将DataTable的列名写入Excel的第一行
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = dataTable.Columns[i].ColumnName;
                }

                // 将DataTable的数据写入Excel
                for (int row = 0; row < dataTable.Rows.Count; row++)
                {
                    for (int col = 0; col < dataTable.Columns.Count; col++)
                    {
                        worksheet.Cells[row + 2, col + 1].Value = dataTable.Rows[row][col];
                    }
                }

                // 保存Excel文件
                FileInfo excelFile = new FileInfo(filePath);
                package.SaveAs(excelFile);
            }

            Console.WriteLine($"Excel文件已保存到：{filePath}");
        }

        public static void Export(DataTable dataTable, string strFileName)
        {
            int rowNum = dataTable.Rows.Count;
            if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
            {
                MessageBox.Show("数据为空");
                return;
            }
            if (rowNum > 0)
            {
                SaveFileDialog saveDlg = new SaveFileDialog();
                saveDlg.Filter = "XLSX文件(*.xlsx)|*.xlsx";
                saveDlg.FileName = strFileName;
                if (saveDlg.ShowDialog() == DialogResult.OK)
                {
                    writeExcel(dataTable, saveDlg.FileName);
                    MessageBox.Show("OK");
                }
            }
        }
    }
}
